<template>
    <div class="production-plan">
        <h3 class="title">生产计划</h3>
        <!-- 基本信息 -->
        <el-form :model="formData" :rules="rules" label-width="120px" ref="formRef">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="*单据主题" prop="documentSubject">
                        <el-input v-model="formData.documentSubject" required></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="单据编号" prop="documentNo">
                        <el-input placeholder="保存后自动生成" readonly v-model="formData.documentNo"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="*关联项目" prop="associatedItemNumber">
                        <el-input placeholder="请输入" suffix-icon="el-icon-search" v-model="formData.associatedItemNumber" required></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="自动生成订单" prop="automaticOrderGeneration">
                        <el-radio-group v-model="formData.automaticOrderGeneration">
                            <el-radio :value="false" label="否"></el-radio>
                            <el-radio :value="true" label="是"></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="*制单人员" prop="documentMaker">
                        <el-input v-model="formData.documentMaker" readonly required></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="*制单日期" prop="documentationDate">
                        <el-date-picker
                            v-model="formData.documentationDate"
                            type="date"
                            required
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="备注 " prop="remark">
                        <el-input v-model="formData.remark" type="textarea" rows="3" required></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item>
                <el-button type="primary" @click="addjihau">保存主表单</el-button>
            </el-form-item>
        </el-form>

        <!-- 生产计划明细 -->
        <div class="detail-section">
            <h4 class="sub-title">生产计划明细</h4>
            <el-button size="small" @click="addNewRow">新增行</el-button>
            <el-button size="small" @click="batchSaveDetails">批量保存明细</el-button>
            <el-table :data="planDetailsList" border style="width: 100%">
                <el-table-column label="产品名称"  width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.productName"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="产品编号" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.productNo"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="规格型号" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.specificationModels"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="单位" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.unit"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="180px">
                    <template #default="{ row }">
                        <el-input-number 
                            v-model.number="row.orderNumber" 
                            :min="0" 
                            controls-position="right"
                        ></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="计划开工日期" width="260px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.constructionPlannedDate"
                            type="date"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="计划完工日期" width="260px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.scheduledCompletionDate"
                            type="date"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="交货日期" width="260px">
                    <template #default="{ row }">
                        <el-date-picker
                            v-model="row.delivery"
                            type="date"
                        ></el-date-picker>
                    </template>
                </el-table-column>
                <el-table-column label="物料清单" width="180px">
                    <template #default="{ row }">
                        <el-input v-model="row.billMaterials"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="备注" width="260px">
                    <template #default="{ row }">
                        <el-input v-model="row.remark" type="textarea" rows="3"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="{ row }">
                        <el-button size="small" type="danger" @click="deleteDetail(row)">删除</el-button>
                        <el-button size="small" type="success" @click="UpdateDetail(row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 附件部分 -->
        <div class="attachment-section">
            <h4 class="sub-title">附件管理</h4>
            <el-button size="small" @click="batchUpload">批量上传</el-button>
            <el-table :data="attachments" border style="width: 100%">
                <el-table-column label="文件名称" prop="fileName"></el-table-column>
                <el-table-column label="文件大小" prop="fileSize"></el-table-column>
                <el-table-column label="上传人" prop="uploader"></el-table-column>
                <el-table-column label="上传时间" prop="uploadTime"></el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { read, write } from '@/axios/axiosHelper';

const formRef = ref(null);
const currentUser = ref("admin"); 
const router = useRouter();
const route = useRoute();

// 主表单数据
const formData = reactive({
    documentNo: "",
    documentSubject: "",
    associatedItemNumber: "",
    automaticOrderGeneration: true,
    documentMaker: currentUser.value,
    documentationDate: new Date().toISOString().split('T')[0],
    remark: "",
    productionPlanningId: null
});

// 主表单验证规则
const rules = reactive({
    documentSubject: [
        { required: true, message: '单据主题不能为空', trigger: 'blur' }
    ],
    associatedItemNumber: [
        { required: true, message: '关联项目不能为空', trigger: 'blur' }
    ],
    documentMaker: [
        { required: true, message: '制单人员不能为空', trigger: 'blur' }
    ],
    documentationDate: [
        { required: true, message: '制单日期不能为空', trigger: 'blur' }
    ],
    remark: [
        { required: true, message: '备注不能为空', trigger: 'blur' }
    ]
});

// 明细数据列表
const planDetailsList = ref([]);

const attachments = ref([]);

// 监听路由参数变化
watch(() => route.query, async (newQuery) => {
    if (newQuery.productionPlanningId) {
        await getProductionById(newQuery.productionPlanningId);
    } else {
        // 清空表单
        formData.documentNo = "";
        formData.documentSubject = "";
        formData.associatedItemNumber = "";
        formData.automaticOrderGeneration = true;
        formData.documentMaker = currentUser.value;
        formData.documentationDate = new Date().toISOString().split('T')[0];
        formData.remark = "";
        formData.productionPlanningId = null;
        planDetailsList.value = [];
    }mainData
});

const getProductionById = async (id) => {
    try {
        const [mainResponse, detailResponse] = await Promise.all([
            read.get('/z-read/api/Management/GetBYIdProduction', {
                params: { productionPlanningId: id }
            }),
            read.get('/z-read/api/Management/GetBYIdProductionScheduleDetail', {
                params: { productionPlanningId: id }
            })
        ]);

        if (mainResponse.data.code === 200) {
            const mainData = mainResponse.data.data[0];
            formData.documentNo = mainData.documentNo;
            formData.documentSubject = mainData.documentSubject;
            formData.associatedItemNumber = mainData.associatedItemNumber;
            formData.automaticOrderGeneration = mainData.automaticOrderGeneration;
            formData.documentMaker = mainData.documentMaker;
            formData.documentationDate = new Date(mainData.documentationDate).toISOString().split('T')[0];
            formData.remark = mainData.remark;
            formData.productionPlanningId = mainData.productionPlanningId;
        }

        if (detailResponse.data.code === 200) {
            planDetailsList.value = detailResponse.data.data.map(item => ({
                productionScheduleDetailId: item.productionScheduleDetailId || '',
                productName: item.productName || '',
                productNo: item.productNo || '',
                specificationModels: item.specificationModels || '',
                unit: item.unit || '',
                orderNumber: item.orderNumber || 0,
                billMaterials: item.billMaterials || '',
                constructionPlannedDate: item.constructionPlannedDate || null,
                scheduledCompletionDate: item.scheduledCompletionDate || null,
                delivery: item.delivery || null,
                remark: item.remark || ''
            }));
        }
    } catch (error) {
        console.error('查询失败:', error);
        ElMessage.error('数据加载失败，请检查网络或联系管理员');
    }
};

// 保存主表单
const addjihau = async () => {
    try {
        const response = await write.put('/z-write/api/Managerment/UpdateProductionPlanning', formData);
        if (response.data.code === 200) {
            formData.productionPlanningId = response.data.data.productionPlanningId;
            ElMessage.success('主表单保存成功');
        } else {
            ElMessage.error(`主表单保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};

// 新增行
const addNewRow = () => {
    planDetailsList.value.push({
        productionScheduleDetailId: null, // 新增行时，初始化为 null，等待后端生成
        productName: "",
        productNo: "",
        specificationModels: "",
        unit: "",
        orderNumber: 0,
        billMaterials: "",
        constructionPlannedDate: null,
        scheduledCompletionDate: null,
        delivery: null,
        remark: "",
        productionPlanningId: null
    });
};

// 批量保存明细
const batchSaveDetails = async () => {
    if (!formData.productionPlanningId) {
        ElMessage.warning('请先保存主表单');
        return;
    }

    const detailsWithId = planDetailsList.value.map(detail => ({
        ...detail,
        productionPlanningId: formData.productionPlanningId
    }));

    try {
        const response = await write.post(
            '/z-write/api/Managerment/AddProductionScheduleDetail',
            detailsWithId
        );
        if (response.data.code === 200) {
            // 更新 planDetailsList 中的 productionScheduleDetailId
            planDetailsList.value = response.data.data.map((item, index) => ({
                ...planDetailsList.value[index],
                productionScheduleDetailId: item.productionScheduleDetailId
            }));
            ElMessage.success('明细批量保存成功');
        } else {
            ElMessage.error(`明细批量保存失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('保存错误:', error);
        ElMessage.error('保存失败，请检查网络或联系管理员');
    }
};

// 修改单条明细
const UpdateDetail = async (row) => {
    if (!formData.productionPlanningId) {
        ElMessage.warning('请先保存主表单');
        return;
    }

    const detailData = {
        ...row,
        productionPlanningId: formData.productionPlanningId
    };

    console.log('发送给后端的明细数据:', detailData); // 打印发送给后端的数据

    try {
        const response = await write.put(
            '/z-write/api/Managerment/UpdateProductionScheduleDetail',
            detailData
        );
        console.log('后端返回的响应:', response); // 打印后端返回的响应

        if (response.data.code === 200) {
            ElMessage.success('明细更新成功');
        } else {
            ElMessage.error(`更新失败：${response.data.message}`);
        }
    } catch (error) {
        console.error('更新错误:', error);
        ElMessage.error('更新失败，请检查网络或联系管理员');
    }
};

// 删除单条明细
const deleteDetail = (row) => {
    ElMessageBox.confirm('确认删除该条明细？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = planDetailsList.value.indexOf(row);
        if (index !== -1) {
            planDetailsList.value.splice(index, 1);
            ElMessage.success('明细删除成功');
        }
    }).catch(() => {
        ElMessage.info('取消删除');
    });
};

const batchUpload = () => {
    ElMessageBox.confirm('确认上传选中文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        ElMessage.info('批量上传功能待完善具体逻辑');
    });
};

onMounted(() => {
    if (route.query.productionPlanningId) {
        getProductionById(route.query.productionPlanningId);
    }
});
</script>

<style scoped>
.production-plan {
    padding: 20px;
}

.title {
    text-align: center;
    margin-bottom: 20px;
}

.sub-title {
    margin: 20px 0 10px;
    font-size: 16px;
    font-weight: 500;
}

.detail-section,
.attachment-section {
    margin-top: 20px;
}

.el-table {
    margin-top: 10px;
}
</style>    